package cn.wygandwdn.core.registry.nacos;

import cn.wygandwdn.core.loadbalancer.LoadBalancer;
import cn.wygandwdn.core.registry.ServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/27 16:53
 */

public class NacosDiscovery implements ServiceDiscovery {
    private static final Logger log = LoggerFactory.getLogger(NacosDiscovery.class);

    private LoadBalancer loadBalancer;

    private NacosDiscovery() {}

    private NacosDiscovery(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
    }

    @Override
    public InetSocketAddress lookupService(String serviceName) {
        List<Instance> allInstances = null;
        try {
            allInstances = NacosUtil.getAllInstances(serviceName);
        } catch (NacosException e) {
            log.error("获取服务实例出错: {}", e);
        }
        log.debug("serviceName: {}", serviceName);
        log.debug("all instances: {}", allInstances);
        Instance instance = loadBalancer.select(allInstances);
        InetSocketAddress address = new InetSocketAddress(instance.getIp(), instance.getPort());
        return address;
    }

    private static NacosDiscovery discovery;

    public static NacosDiscovery getInstance(LoadBalancer loadBalancer) {
        if (discovery == null) {
            synchronized (NacosDiscovery.class) {
                if (discovery == null) {
                    discovery = new NacosDiscovery(loadBalancer);
                }
            }
        }
        return discovery;
    }
}
